/* global window */
/* global document */
import React from 'react';
import NProgress from 'nprogress';
import PropTypes from 'prop-types';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';
import { Loader, MyLayout } from 'components';
import { BackTop, Layout, Modal, Input, message, notification, Icon } from 'antd';
import { classnames, config } from 'utils';
import { Helmet } from 'react-helmet';
import { routerRedux, withRouter } from 'dva/router';
import Error from './error';
import '../themes/index.less';
import './app.less';
import MD5 from 'js-md5';
const confirm = Modal.confirm;
const { Content, Footer, Sider } = Layout;
const { Header, Bread, styles } = MyLayout;
const { openPages, name, wsUrl } = config;


const App = ({
    children,
    dispatch,
    app,
    loading,
    location,
}) => {
    const {
        user, siderFold, darkTheme, isNavbar, menuPopoverVisible, navOpenKeys, menu, permissions, loader,
    } = app;
    let { pathname } = location;
    pathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
    const { iconFontJS, iconFontCSS, logo } = config;
    const current = menu.filter(item => pathToRegexp(item.route || '').exec(pathname));
    if (current.length === 0) {
        current.push(app.menu[0]); // 默认进入首页
    }
    // const hasPermission = current.length ? permissions.visit.includes(current[0].id) : false
    const hasPermission = true;

    let pwd, pwdtow;
    const headerProps = {
        menu,
        user,
        location,
        siderFold,
        isNavbar,
        menuPopoverVisible,
        navOpenKeys,
        switchMenuPopover () {
            dispatch({ type: 'app/switchMenuPopver' });
        },
        logout () {
            dispatch({ type: 'app/logout' });
        },
        login () {
            dispatch(routerRedux.push({ pathname: '/login' }));
        },
        gotoUserInfo () {
            confirm({
                title: <span><span style={{ color: 'red' }}>*</span>修改密码:</span>,
                cancelText: '取消',
                okText: '确定',
                content: <div>
                    <Input type="password" style={{ width: 160 }} onChange={e => pwd = e.target.value} placeholder="请输入密码" />
                    <Input type="password" style={{ width: 160, marginTop: 10 }} onChange={e => pwdtow = e.target.value} placeholder="确认密码" />
                </div>,
                onOk () {
                    if (pwd === pwdtow) {
                        dispatch({ type: 'app/gotoUserInfo', payload: { newPwd: MD5(pwdtow) } });
                    } else {
                        message.error('两次密码不一致');
                    }
                },
                onCancel () {
                    console.log('Cancel');
                },
            });
        },
        switchSider () {
            dispatch({ type: 'app/switchSider' });
        },
        changeOpenKeys (openKeys) {
            dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } });
        },
    };

    const siderProps = {
        menu,
        location,
        siderFold,
        darkTheme,
        navOpenKeys,
        changeTheme () {
            dispatch({ type: 'app/switchTheme' });
        },
        changeOpenKeys (openKeys) {
            window.localStorage.setItem('navOpenKeys', JSON.stringify(openKeys));
            dispatch({ type: 'app/handleNavOpenKeys', payload: { navOpenKeys: openKeys } });
        },
    };

    const breadProps = {
        menu,
        location,
    };
    if (openPages && openPages.includes(pathname)) {
        loader && setTimeout(() => dispatch({ type: 'app/loaderFun' }), 1000);
        if (loading.global) {
            NProgress.start();
        } else {
            NProgress.done();
        }
        return (<div>
            {loader && <Loader fullScreen spinning />}
            <div style={{ display: loader ? 'none' : 'block' }}>{children}</div>
        </div>);
    }
    loader && setTimeout(() => dispatch({ type: 'app/loaderFun' }), 1000);
    if (loading.global) {
        NProgress.start();
    } else {
        NProgress.done();
    }


    return (
        <div>
            {loader && <Loader fullScreen spinning />}
            <div style={{ display: loader ? 'none' : 'block' }}>
                <Helmet>
                    <title>{name}</title>
                    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                    <link rel="icon" href={logo} type="image/x-icon" />
                    {iconFontJS && <script src={iconFontJS} />}
                    {iconFontCSS && <link rel="stylesheet" href={iconFontCSS} />}
                </Helmet>
                <Layout
                    style={{ height: '100vh' }}
                    className={classnames({ [styles.dark]: darkTheme, [styles.light]: !darkTheme })}
                >
                    {!isNavbar && <Sider
                        trigger={null}
                        collapsible
                        collapsed={siderFold}
                    >
                        {siderProps.menu.length === 0 ? null : <MyLayout.Sider {...siderProps} />}
                    </Sider>}
                    <Layout id="mainContainer">
                        <BackTop target={() => document.getElementById('mainContainer')} />
                        <Header {...headerProps} />
                        <Content style={{ height: '84vh' }}>
                            {breadProps.location.pathname !== '/home' && <Bread {...breadProps} />}
                            {hasPermission ? children : <Error />}
                        </Content>
                        <Footer>
                            {config.footerText}
                        </Footer>
                    </Layout>
                </Layout>
                <WebScketPages dispatch={dispatch} />
            </div>
        </div>
    );
};


App.propTypes = {
    children: PropTypes.element.isRequired,
    location: PropTypes.object,
    dispatch: PropTypes.func,
    app: PropTypes.object,
    loading: PropTypes.object,
};

export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App));


//websocket组件
class WebScketPages extends React.Component {
    componentWillMount () {
        let { dispatch } = this.props;
        //监听浏览器前进后退
        window.addEventListener('popstate', () => {
            if(location.pathname.split("_list").length >1 && !location.pathname.split("_list")[1]){
                let path = location.pathname.split('/')[1].split('_list')[0];
                dispatch({
                    type: 'app/goToPath',
                    payload: path,
                });
            }
        });
        // console.log('进来了',JSON.parse(localStorage.getItem('userInfor')))
        let sid = JSON.parse(localStorage.getItem('userInfor'));
        //这一步是连接后台WebSocket连接,相对http协议接口他是ws开头,https时是wss开头
        if (window.WebSocket && sid && localStorage.getItem('webSocket')) {
            const ws = new window.WebSocket(`${wsUrl}//topic/${sid && sid.sessionId}`);
            //判断连接是否成功
            ws.onopen = function (e) {
                console.log("连接服务器成功");
                ws.send("success");
                localStorage.removeItem('webSocket');
            };
            //抛出连接异常
            ws.onclose = function (e) { console.log("服务器异常", e); };
            //连接失败时回调函数
            ws.onerror = function () { console.log("连接出错"); };
            //连接成功是回调函数,并返回传输数据
            ws.onmessage = function (e) {
                let msg = JSON.parse(e.data);
                // console.log(2222,msg)
                notification.open({
                    message: msg.titleText,
                    description: msg.message,
                    // duration: 0,
                    icon: <Icon type="smile" style={{ color: '#108ee9' }} />,
                    onClick: () => {
                        if (msg.linktext) {
                            //跳转详情
                            localStorage.setItem("id", msg.linktext);
                            dispatch({
                                type: 'app/goToPath',
                                payload: msg.type == '提醒' ? "Privilege_list" : "home_list",
                            });
                        } else {
                            //跳转列表
                            dispatch({
                                type: 'app/goToPath',
                                payload: msg.type == '提醒' ? "Privilege_management" : "home",
                            });
                        }
                    },
                });
            };
        }
    }
    render () { return <div/>; }
}